package com.uinnova.product.eam.workable.listener;

import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component("reSubmitToRejectUserListener")
public class ReSubmitToRejectUserListener implements ExecutionListener {

    @Autowired
    private transient HistoryService historyService;

    @Override
    public void notify(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .orderByHistoricTaskInstanceEndTime().asc().list()
                .stream().filter(hTask -> !"MI_END".equals(hTask.getDeleteReason())).collect(Collectors.toList());
        //过滤掉自动关闭任务
        String assignee = list.get(list.size()-1).getAssignee();
        Map<String, Object> variables = execution.getVariables();
        variables.put("assignee", assignee);
        execution.setVariables(variables);
    }
}
